﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IMS_Data
{
    public class CompanyReposity
    {
        public company GetCompany(string name)
        {
            using (IMS_Data.IMS_DBEntities ctx = new IMS_Data.IMS_DBEntities())
            {
                return  (from o in ctx.company where o.company_name == name select o).FirstOrDefault();
            }
        }
        public company GetCompany(int  index)
        {
            using (IMS_Data.IMS_DBEntities ctx = new IMS_Data.IMS_DBEntities())
            {
                return (from o in ctx.company where o.index_id == index select o).FirstOrDefault();
            }
        }
        public IList<company> QueryCompany(string sql)
        {
            using (IMS_Data.IMS_DBEntities ctx = new IMS_Data.IMS_DBEntities())
            {
                var eles = ctx.ExecuteStoreQuery<company>(sql);

                return eles.ToList<company>();
            }
        }
        public IList<company> GetCompanies()
        {
            using (IMS_Data.IMS_DBEntities ctx = new IMS_Data.IMS_DBEntities())
            {
                return ctx.company.ToList();
            }
        }
        public void AddCompany(company cp)
        {
            using (IMS_Data.IMS_DBEntities ctx = new IMS_Data.IMS_DBEntities())
            {
                ctx.company.AddObject(cp);
                ctx.SaveChanges();
            }
        }

        public void DeleteCompany(company cp)
        {
            using (IMS_Data.IMS_DBEntities ctx = new IMS_Data.IMS_DBEntities())
            {
                ctx.AttachTo(ctx.DefaultContainerName + ".company", cp);
                ctx.company.DeleteObject(cp);
                ctx.SaveChanges();
            }
        }

        public void UpdateCompany(company cp)
        {
            using (IMS_Data.IMS_DBEntities ctx = new IMS_Data.IMS_DBEntities())
            {

                ctx.company.Attach(cp);

                ctx.ObjectStateManager.ChangeObjectState(cp, System.Data.EntityState.Modified);
                
                ctx.SaveChanges();
            }
        }
    }
}
